package com.mdd.front.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.LogIntegral;
import com.mdd.common.entity.log.LogEarnings;
import com.mdd.common.entity.log.LogMoney;
import com.mdd.common.entity.order.OrderGoods;
import com.mdd.common.enums.LogMoneyEnum;
import com.mdd.common.mapper.LogIntegralMapper;
import com.mdd.common.mapper.log.LogEarningsMapper;
import com.mdd.common.mapper.log.LogMoneyMapper;
import com.mdd.common.mapper.order.OrderGoodsMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.service.ILogsService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.vo.distribution.DistributionEarningsRecordVo;
import com.mdd.front.vo.recharge.RechargeRecordVo;

@Service
public class LogsServiceImpl implements ILogsService {

	@Resource
	LogMoneyMapper logMoneyMapper;

	@Resource
	LogEarningsMapper logEarningsMapper;

	@Resource
	OrderGoodsMapper orderGoodsMapper;

	@Resource
	OrderMapper orderMapper;
	
	@Resource
	LogIntegralMapper logIntegralMapper;


	@Override
	public PageResult<RechargeRecordVo> userMoney(PageValidate pageValidate, Integer userId, Integer type) {
		Integer pageNo   = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();

		QueryWrapper<LogMoney> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		queryWrapper.orderByDesc("id");
		if (type > 0) {
			queryWrapper.eq("action", type);
		}

		IPage<LogMoney> iPage = logMoneyMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

		List<RechargeRecordVo> list = new LinkedList<>();
		for (LogMoney logMoney : iPage.getRecords()) {
			RechargeRecordVo vo = new RechargeRecordVo();

			vo.setId(logMoney.getId());
			vo.setAction(logMoney.getAction());
			vo.setOrderAmount(logMoney.getChangeAmount());
			vo.setTips(LogMoneyEnum.getMsgByCode(logMoney.getChangeType()));
			vo.setCreateTime(TimeUtils.timestampToDate(logMoney.getCreateTime()));
			list.add(vo);
		}

		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
	}
	
	@Override
	public PageResult<DistributionEarningsRecordVo> userEarnings(PageValidate pageValidate, Integer userId, Integer type, String queryTime) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();

		MPJQueryWrapper<LogIntegral> queryWrapper = new MPJQueryWrapper<>();
		queryWrapper.leftJoin("?_order o ON t.source_sn=o.order_sn".replace("?_", GlobalConfig.tablePrefix));
		//        queryWrapper.leftJoin("?_order_goods og ON o.id=og.order_id".replace("?_", GlobalConfig.tablePrefix));
		queryWrapper.leftJoin("?_user u ON t.user_id=u.id".replace("?_", GlobalConfig.tablePrefix));
		queryWrapper.select("t.id,t.change_type,t.change_amount,t.left_amount,t.action," +
				"o.id as order_id,o.goods_num,o.pay_money,t.create_time,u.nickname as buy_username,u.mobile as buy_phone");
//		queryWrapper.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		queryWrapper.eq("t.user_id", userId);
		queryWrapper.eq("change_type", LogMoneyEnum.UI_INC_GOODS.getCode());
		queryWrapper.orderByDesc("t.id");
		if (type > 0) {
			queryWrapper.eq("t.action", 1);
		}
		if(!StringUtils.isEmpty(queryTime)){
			queryWrapper.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m')",queryTime);
		}

		IPage<LogIntegral> iPage = logIntegralMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

	
		List<DistributionEarningsRecordVo> list = new LinkedList<>();
		HashMap<String, Object> resultMap = new HashMap<>();

		for (LogIntegral logEarnings : iPage.getRecords()) {
			DistributionEarningsRecordVo vo = new DistributionEarningsRecordVo();
			BeanUtils.copyProperties(logEarnings, vo);
			vo.setId(logEarnings.getId());
			vo.setAction(logEarnings.getAction());
			vo.setOrderAmount(logEarnings.getChangeAmount());
			if(logEarnings.getOrderId()!=null && logEarnings.getOrderId()>0){
				QueryWrapper<OrderGoods> orderGoodsQueryWrapper=new QueryWrapper<>();
				orderGoodsQueryWrapper.eq("order_id",logEarnings.getOrderId());
				orderGoodsQueryWrapper.select("id,goods_name");
				List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
				List<String> goodesList = new ArrayList<>();
				orderGoods.forEach(item->{
					goodesList.add(item.getGoodsName());
				});
				vo.setGoodsName(goodesList);
			}else {
				List<String> goodesList = new ArrayList<>();
				goodesList.add("快递下单");
				vo.setGoodsName(goodesList);
//				vo.setGoodsNum(1);
//				vo.setPayMoney(BigDecimal.TEN);
			}

			//            vo.setTips(LogEarningsEnum.getMsgByCode(logEarnings.getChangeType()));
			vo.setCreateTime(TimeUtils.timestampToDate(logEarnings.getCreateTime()));
			list.add(vo);
		}

		resultMap.put("buyNumber",0);
		resultMap.put("totalAmountCount",0);
		resultMap.put("shareAmount",0);

		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list,resultMap);
	}
	
	@Override
	public PageResult<DistributionEarningsRecordVo> userEarningsAdd(PageValidate pageValidate, Integer userId, Integer type, String queryTime) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();

		MPJQueryWrapper<LogEarnings> queryWrapper = new MPJQueryWrapper<>();
		queryWrapper.leftJoin("?_order o ON t.source_sn=o.order_sn".replace("?_", GlobalConfig.tablePrefix));
		//        queryWrapper.leftJoin("?_order_goods og ON o.id=og.order_id".replace("?_", GlobalConfig.tablePrefix));
		queryWrapper.leftJoin("?_user u ON t.user_id=u.id".replace("?_", GlobalConfig.tablePrefix));
		queryWrapper.select("t.id,t.change_type,t.change_amount,t.left_amount,t.action," +
				"o.id as order_id,o.goods_num,o.pay_money,t.create_time,u.nickname as buy_username,u.mobile as buy_phone");
//		queryWrapper.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		queryWrapper.eq("t.user_id", userId);
		queryWrapper.eq("change_type", LogMoneyEnum.UE_INC_GOODS.getCode());
		queryWrapper.orderByDesc("t.id");
		if (type > 0) {
			queryWrapper.eq("t.action", 1);
		}
		if(!StringUtils.isEmpty(queryTime)){
			queryWrapper.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m')",queryTime);
		}

		IPage<LogEarnings> iPage = logEarningsMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

	
		List<DistributionEarningsRecordVo> list = new LinkedList<>();
		HashMap<String, Object> resultMap = new HashMap<>();

		for (LogEarnings logEarnings : iPage.getRecords()) {
			DistributionEarningsRecordVo vo = new DistributionEarningsRecordVo();
			BeanUtils.copyProperties(logEarnings, vo);
			vo.setId(logEarnings.getId());
			vo.setAction(logEarnings.getAction());
			vo.setOrderAmount(logEarnings.getChangeAmount());
			if(logEarnings.getOrderId()!=null && logEarnings.getOrderId()>0){
				QueryWrapper<OrderGoods> orderGoodsQueryWrapper=new QueryWrapper<>();
				orderGoodsQueryWrapper.eq("order_id",logEarnings.getOrderId());
				orderGoodsQueryWrapper.select("id,goods_name");
				List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
				List<String> goodesList = new ArrayList<>();
				orderGoods.forEach(item->{
					goodesList.add(item.getGoodsName());
				});
				vo.setGoodsName(goodesList);
			}

			//            vo.setTips(LogEarningsEnum.getMsgByCode(logEarnings.getChangeType()));
			vo.setCreateTime(TimeUtils.timestampToDate(logEarnings.getCreateTime()));
			list.add(vo);
		}

		resultMap.put("buyNumber",0);
		resultMap.put("totalAmountCount",0);
		resultMap.put("shareAmount",0);

		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list,resultMap);
	}

//	@Override
	public PageResult<DistributionEarningsRecordVo> userEarnings1(PageValidate pageValidate, Integer userId, Integer type, String queryTime) {
		Integer pageNo = pageValidate.getPageNo();
		Integer pageSize = pageValidate.getPageSize();

		MPJQueryWrapper<LogEarnings> queryWrapper = new MPJQueryWrapper<>();
		queryWrapper.leftJoin("?_order o ON t.source_sn=o.order_sn".replace("?_", GlobalConfig.tablePrefix));
		//        queryWrapper.leftJoin("?_order_goods og ON o.id=og.order_id".replace("?_", GlobalConfig.tablePrefix));
		queryWrapper.leftJoin("?_user u ON t.user_id=u.id".replace("?_", GlobalConfig.tablePrefix));
		queryWrapper.select("t.id,t.change_type,t.change_amount,t.left_amount,t.action," +
				"o.id as order_id,o.goods_num,o.pay_money,t.create_time,u.nickname as buy_username,u.mobile as buy_phone");
//		queryWrapper.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		queryWrapper.eq("t.user_id", userId);
		queryWrapper.orderByDesc("t.id");
		if (type > 0) {
			queryWrapper.eq("t.action", 1);
		}
		if(!StringUtils.isEmpty(queryTime)){
			queryWrapper.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m')",queryTime);
		}

		IPage<LogEarnings> iPage = logEarningsMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
		MPJQueryWrapper<LogEarnings> queryWrapperCount = new MPJQueryWrapper<>();
		queryWrapperCount.leftJoin("?_order o ON t.source_sn=o.order_sn".replace("?_", GlobalConfig.tablePrefix));
//		queryWrapperCount.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		queryWrapperCount.eq("t.user_id", userId);
		if(!StringUtils.isEmpty(queryTime)){
			queryWrapperCount.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m')",queryTime);
		}
		if (type > 0) {
			queryWrapperCount.eq("t.action", 1);
		}
		queryWrapperCount.select("count(0) as buyNumber");
		//Long buyNumber = logEarningsMapper.selectCount(queryWrapperCount);
		
		Map<String, Object> map1 = logEarningsMapper.selectMaps(queryWrapperCount).get(0);
		Long buyNumber = 0L;
		if(null != map1) {
			buyNumber = (Long) map1.get("buyNumber");
		}


		MPJQueryWrapper<LogEarnings> queryWrapperAmountCount = new MPJQueryWrapper<>();
		queryWrapperAmountCount.leftJoin("?_order o ON t.source_sn=o.order_sn".replace("?_", GlobalConfig.tablePrefix));
//		queryWrapperAmountCount.eq("o.order_status", OrderEnum.ORDER_STATUS_COMPLETED.getCode());
		queryWrapperAmountCount.eq("t.user_id", userId);
		queryWrapperAmountCount.eq("pay_is",1);
		if(!StringUtils.isEmpty(queryTime)){
			queryWrapperAmountCount.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m-%d')",queryTime);
		}
		if (type > 0) {
			queryWrapperAmountCount.eq("t.action", 1);
		}
		queryWrapperAmountCount.select("sum(pay_money) payMoney");
		Map<String, Object> map = logEarningsMapper.selectMaps(queryWrapperAmountCount).get(0);
		BigDecimal totalAmountCount = BigDecimal.ZERO;
		if(null != map) {
			totalAmountCount = (BigDecimal) map.get("payMoney");
		}


		MPJQueryWrapper<LogEarnings> queryShareAmount = new MPJQueryWrapper<>();
		queryShareAmount.leftJoin("?_order o ON t.source_sn=o.order_sn".replace("?_", GlobalConfig.tablePrefix));
		queryShareAmount.eq("t.user_id",userId);
		if(!StringUtils.isEmpty(queryTime)){
			queryShareAmount.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m-%d')",queryTime);
		}
		if (type > 0) {
			queryShareAmount.eq("t.action", 1);
		}
		queryShareAmount.orderByDesc("t.create_time");
		queryShareAmount.last("limit 1");
		queryShareAmount.select("t.id,t.sn,t.user_id,t.source_id,t.source_sn,t.change_type,t.change_amount,t.left_amount,t.action,t.remark,t.extra,t.create_time,t.update_time,t.delete_time");
		LogEarnings logEarnings1 = logEarningsMapper.selectOne(queryShareAmount);

		BigDecimal shareAmount=BigDecimal.ZERO;
		if(logEarnings1!=null){
			shareAmount=logEarnings1.getLeftAmount();
		}
		List<DistributionEarningsRecordVo> list = new LinkedList<>();
		HashMap<String, Object> resultMap = new HashMap<>();

		for (LogEarnings logEarnings : iPage.getRecords()) {
			DistributionEarningsRecordVo vo = new DistributionEarningsRecordVo();
			BeanUtils.copyProperties(logEarnings, vo);
			vo.setId(logEarnings.getId());
			vo.setAction(logEarnings.getAction());
			vo.setOrderAmount(logEarnings.getChangeAmount());
			if(logEarnings.getOrderId()!=null && logEarnings.getOrderId()>0){
				QueryWrapper<OrderGoods> orderGoodsQueryWrapper=new QueryWrapper<>();
				orderGoodsQueryWrapper.eq("order_id",logEarnings.getOrderId());
				orderGoodsQueryWrapper.select("id,goods_name");
				List<OrderGoods> orderGoods = orderGoodsMapper.selectList(orderGoodsQueryWrapper);
				List<String> goodesList = new ArrayList<>();
				orderGoods.forEach(item->{
					goodesList.add(item.getGoodsName());
				});
				vo.setGoodsName(goodesList);
			}

			//            vo.setTips(LogEarningsEnum.getMsgByCode(logEarnings.getChangeType()));
			vo.setCreateTime(TimeUtils.timestampToDate(logEarnings.getCreateTime()));
			list.add(vo);
		}

		resultMap.put("buyNumber",buyNumber);
		resultMap.put("totalAmountCount",totalAmountCount);
		resultMap.put("shareAmount",shareAmount);

		return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list,resultMap);
	}

}
